import React, { useEffect, useRef } from "react";
// import { init } from "echarts";
import * as echarts from "echarts";
import axios from "axios";

import "./index.scss";

export default function Dashboard() {
  const mainRef = useRef();

  useEffect(() => {
    function getData() {
      // 展示加载中
      myEchart.showLoading();
      axios
        .get("/a.json")
        .then((response) => {
          const { data } = response.data;
          // setOption 内部会有合并的操作
          myEchart.setOption({
            yAxis: {
              data: data.categorys,
            },
            series: [
              {
                name: "上月",
                data: data.prev,
              },
              {
                name: "本月",
                data: data.now,
              },
            ],
          });
        })
        .finally(() => {
          // 隐藏加载中
          myEchart.hideLoading();
        });
    }

    // 1. 实例化一个 echarts 实例
    // const myEchart = echarts.init(document.querySelector("#main"));
    const myEchart = echarts.init(mainRef.current);

    // 2. setOption
    myEchart.setOption({
      title: {
        text: "月度销量对比",
        subtext: "近期主要商品",
      },
      legend: {
        bottom: 10,
      },
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "value",
      },
      yAxis: {
        type: "category",
        data: [],
      },
      series: [
        {
          name: "本月",
          zlevel: 2,
          stack: "1",
          stackStrategy: "negative",
          data: [],
          type: "bar",
          barWidth: "40",
          itemStyle: {
            color: "#36A3F7",
          },
        },
        {
          name: "上月",
          zlevel: 1,
          stack: "1",
          stackStrategy: "negative",
          data: [],
          type: "bar",
          barWidth: "40",
          itemStyle: {
            color: "#EDAF51",
          },
        },
      ],
    });

    // 3. 获取数据
    getData();
  }, []);

  return (
    <div className="dashboard">
      <h1>仪表盘 - 图表</h1>

      <div ref={mainRef} style={{ width: "600px", height: "400px" }}></div>
    </div>
  );
}
